import type { Directive, DirectiveBinding } from 'vue';

import { useUserStore } from '@/stores/user';
import { AdminType } from '@/types/permission';
import type { PermissionDirectiveBinding } from '@/types/permission';

/**
 * 权限指令 - 基于AdminType的权限控制
 *
 * 使用示例：
 * <!-- 仅超级管理员可见 -->
 * <a-button v-permission="{ adminTypes: [AdminType.SUPER_ADMIN] }">
 *   系统配置
 * </a-button>
 *
 * <!-- 需要特定租户权限 -->
 * <a-button v-permission="{ tenantId: 'tenant-123' }">
 *   管理此学校
 * </a-button>
 *
 * <!-- 组合权限检查 -->
 * <a-button v-permission="{
 *   adminTypes: [AdminType.SCHOOL_ADMIN],
 *   tenantId: 'tenant-123'
 * }">
 *   管理指定学校
 * </a-button>
 */

/**
 * 检查权限的核心函数
 */
function checkPermission(binding: PermissionDirectiveBinding): boolean {
  const userStore = useUserStore();
  const { adminTypes, tenantId } = binding;

  // 如果用户未登录，默认无权限
  if (!userStore.isLoggedIn || !userStore.adminType) {
    return false;
  }

  let hasPermission = true;

  // 检查管理员类型权限
  if (adminTypes && adminTypes.length > 0) {
    if (!adminTypes.includes(userStore.adminType)) {
      hasPermission = false;
    }
  }

  // 检查租户权限
  if (tenantId && hasPermission) {
    if (!userStore.hasTenantAccess(tenantId)) {
      hasPermission = false;
    }
  }

  return hasPermission;
}

/**
 * 权限指令实现
 */
export const vPermission: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding<PermissionDirectiveBinding>) {
    const hasPermission = checkPermission(binding.value || {});

    if (!hasPermission) {
      // 移除元素或隐藏元素
      if (el.parentNode) {
        el.parentNode.removeChild(el);
      } else {
        el.style.display = 'none';
      }
    }
  },

  updated(el: HTMLElement, binding: DirectiveBinding<PermissionDirectiveBinding>) {
    const hasPermission = checkPermission(binding.value || {});

    if (!hasPermission) {
      if (el.style.display !== 'none') {
        el.style.display = 'none';
      }
    } else {
      if (el.style.display === 'none') {
        el.style.display = '';
      }
    }
  }
};

/**
 * 权限检查组合函数 - 供组件内部使用
 */
export function usePermission() {
  const userStore = useUserStore();

  /**
   * 检查是否为指定的管理员类型
   */
  const isAdminType = (adminType: AdminType): boolean => {
    return userStore.adminType === adminType;
  };

  /**
   * 检查是否为指定管理员类型之一
   */
  const isOneOfAdminTypes = (adminTypes: AdminType[]): boolean => {
    if (!userStore.adminType) return false;
    return adminTypes.includes(userStore.adminType);
  };

  /**
   * 检查是否有指定租户的权限
   */
  const hasTenant = (tenantId: string): boolean => {
    if (!userStore.adminType) return false;
    return userStore.hasTenantAccess(tenantId);
  };

  /**
   * 检查是否为超级管理员
   */
  const isSuperAdmin = (): boolean => {
    return userStore.isSuperAdmin;
  };

  /**
   * 检查是否为学校管理员
   */
  const isSchoolAdmin = (): boolean => {
    return userStore.isSchoolAdmin;
  };

  /**
   * 综合权限检查
   */
  const checkPermissions = (config: PermissionDirectiveBinding): boolean => {
    return checkPermission(config);
  };

  return {
    isAdminType,
    isOneOfAdminTypes,
    hasTenant,
    isSuperAdmin,
    isSchoolAdmin,
    checkPermissions,

    // 直接暴露用户状态
    adminType: userStore.adminType,
    managedTenantIds: userStore.managedTenantIds,
    currentTenant: userStore.currentTenant,
    accessibleTenants: userStore.accessibleTenants
  };
}

/**
 * 默认导出权限指令
 */
export default vPermission;
